<template>
  <div>
    <div>
      <!-- 1. show-checkbox 显示选择框
            2. default-expand-all 默认展开
            3. check-strictly  设置true，可以关闭父子关联
        -->
      <el-tree
        ref="tree"
        v-loading="loading"
        :data="permissionList"
        :props="{ label: 'name'}"
        node-key="id"
        default-expand-all
        show-checkbox
        check-strictly
        style="min-height: 300px"
      />
    </div>

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { tranlistToTreeData } from '@/utils'
import { getRoleId, assignPerm } from '@/api/setting'
export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      permissionList: [], // 权限列表
      loading: false
    }
  },
  created() {
    this.getPermissionList()
    this.getRoleId()
  },

  methods: {
    // 获取当前已选权限
    async getRoleId() {
      this.loading = true
      const res = await getRoleId(this.roleId)
      this.$refs.tree.setCheckedKeys(res.data.permIds)
      this.loading = false
    },

    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionList()
      this.permissionList = tranlistToTreeData(res.data)
    },

    // 取消按钮
    cancelButton() {
      this.$emit('close')
    },

    // 设置权限按钮
    async setRolesBtn() {
      const permIds = this.$refs.tree.getCheckedKeys()
      const res = await assignPerm({ id: this.roleId, permIds })

      // 给用户提示,关闭弹窗
      this.$message.success(res.message)
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 30px;
}
</style>
